<?php

include_once 'lib/WebServices/Proxy.php';
include_once 'lib/HTML/FormElements.php';

abstract class Controller {
  protected $attributes = array();
  protected $model;
  protected $fe;
  protected $result;
  protected $error = false;
  
  protected function Controller(){ }
  
  protected function model(){
    if($this->model == null)
      throw new MTException('null Model pointer');
    return $this->model;
  }
  
  public function uword($str){
    return ucwords(mb_strtolower($str,'UTF-8'));
  }
  
  protected function checkInput($name,$min_max=false,$html_specials=false,$regex=false,$replaceSpace=false){
   $input = trim(stripslashes($this->getAttribute($name)));
   
   if(!strlen($input)
      || (is_array($min_max) && (strlen($input)<$min_max[0] || strlen($input)>$min_max[1]))
      || ($regex && !preg_match($regex, $input)))
   {
     $this->fe->setError($name, 'false');
     return;
   }
    
    if($html_specials)      
      $input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
    if($replaceSpace)
      $input = preg_replace('/\s/', '', $input);
    
    $this->setAttribute($name, $input);
  }

  public function id(){
  	return $this->model()->id;
  }
  
  public function set($attr){
    
    $this->model()->set($attr);
  }
  
  public function reset($attr=null){

    $this->model()->reset($attr);
  }
  
  public function getAttribute($name=null){

    return $this->model()->getAttribute($name);
  }
  
  public function setAttribute($name, $val){

    $this->model()->setAttribute($name, $val);
  }
  
  public function add(){
   
    $this->result = $this->model()->add();
    return $this;
  }
  
  public function get(){

    $this->result = $this->model()->get(); 
    return $this;
  }
  
  public function delete(){
    
    $this->model()->delete();
    unset($this->model);
    return $this;
  }
  
  public function update($attr,$insert_into_attr=true){ 
  	
    $this->model()->update($attr,$insert_into_attr);
    
    if($insert_into_attr && $this->result){
      foreach($attr as $name=>$val)
        $this->result->$name = $val;
    }
    return $this;
  }
  
  public function send(){
  	
    if($this->error)
      Proxy::send('<proxy id="response"><error>'.$e->getMessage().'</error></proxy>');
    else
      Proxy::send('<proxy id="response"><result>'.$this->result.'</result></proxy>');
    
  }
  
  public function result(){
  	return $this->result;
  }
  
  public function getDetails(){
    $this->result = $this->model()->getDetails();
    return $this;
  }
  
  public function getInputErrors(){
  	return $this->fe->getFormErrors();
  }
  
  public function getTime(){
    $date = preg_split('(-|:|\s)',$this->result()->time_added,6);
    return date("M d\<\s\u\p\>S\<\/\s\u\p\> Y", mktime(0, 0, 0, (int)$date[1], (int)$date[2], (int)$date[0]));
  }
}

?>
